#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
#include <cstdlib>
#include "log.hpp"

// 共享内存大小一般建议是4096的整数倍
#define SHMSIZE 4096 

const std::string pathname = "/home/zmh01";
const int proj_id = 0x6666;

Log log;

key_t GetKey(){
    // 生成共享内存的键值key
    key_t k = ftok(pathname.c_str(), proj_id);
    if(k < 0){
        log(Fatal, "create key error: %s", strerror(errno));
        exit(1);
    }
    log(INFO, "create key success, key: %d", k);
    return k;
}

int GetShareMemHelper(int flag){
    int shmid = shmget(GetKey(), SHMSIZE, flag);
    if (shmid < 0){
        log(Fatal, "create share memory error: %s", strerror(errno));
        exit(2);
    }
    log(INFO, "create share memory success, shmid: %d", shmid);
    return shmid;
}

// 一个创建
int CreateShm(){
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

// 一个获取
int GetShm(){
    return GetShareMemHelper(IPC_CREAT);
}

#endif